//
//  SWOrderDetailViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/19.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWOrderDetailViewController: SWBaseViewController,SWAPIComponent,NullDataStatusProtocol,ClickActionDelegate
{
    var nullDataView:UIView?
    
    
    private var _orderID:String
    
    private var _status:SWOrderStatus = .unknow{
        didSet{
            if _status != oldValue
            {
                _statusView?.status = _status
                createBottomView(status: _status)
            }
        }
    }
    
    private var _bottomView:UIView?{
        willSet{
            _bottomView?.removeFromSuperview()
        }
        didSet{
            if let bottomView = _bottomView
            {
                _container.addSubview(bottomView)
                _container.contentSize = CGSizeMake(view.width, bottomView.bottom)
            }
        }
    }
    
    private var _statusView:SWOrderStatusView?
    lazy private var _container:UIScrollView = UIScrollView()
    private var _headerView:UIView = UIView()
    private var _titleLabel:UILabel = UILabel()
    private var _imageView:ImageLoader = ImageLoader()
    private var _orderLabel:UILabel = UILabel()
    private var _dateLabel:UILabel = UILabel()
    private var _priceLabel:UILabel = UILabel()
    
    init(orderID:String)
    {
        _orderID = orderID
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        SWNotificationCenter.removeObserver(self)
        trace("DEINIT SWOrderDetailViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "订单详情"
        automaticallyAdjustsScrollViewInsets = false
        
        
        _container.frame = view.bounds
        _container.alwaysBounceVertical = true
        _container.contentInset = UIEdgeInsetsMake(navigationBarBottom, 0, 0, 0)
        view.addSubview(_container)
        
        setupRefreshControl()
        
        createHeaderView()
        
        nullDataViewSetup()
        
        //支付完成
        SWNotificationCenter.addObserver(self, selector: #selector(paySuccessNotification(_:)), name: NotificationName.PaySuccess, object: nil)
        
        //上传进度
        SWNotificationCenter.addObserver(self, selector: #selector(uploadProgressChangedNotification(_:)), name: NotificationName.UploadProgressChanged, object: nil)
        
        //上传保存完成
        SWNotificationCenter.addObserver(self, selector: #selector(orderPagesUpdateCompleteNotification(_:)), name: NotificationName.OrderPagesUpdateComplete, object: nil)
        
        if _orderID != ""
        {
            beginRefreshing()
        }
    }
    
    
    private func createHeaderView()
    {
        _headerView.frame = CGRectMake(0, 0, view.width, 280)
        _container.addSubview(_headerView)
        
        _imageView.frame = CGRectMake(0, 0, 40, 40)
        _headerView.addSubview(_imageView)
        
        let titleLabelX:CGFloat = _imageView.right + 10
        let titleLabelWidth:CGFloat = view.width - titleLabelX
        _titleLabel.frame = CGRectMake(titleLabelX, 0, titleLabelWidth, 18)
        _titleLabel.font = UIFont.systemFont(ofSize: 14)
        _headerView.addSubview(_titleLabel)
        
        _orderLabel.frame = CGRectMake(0, _imageView.bottom + 10, view.width * 0.5, 16)
        _orderLabel.font = UIFont.systemFont(ofSize: 12)
        _orderLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_orderLabel)
        
        _dateLabel.frame = CGRectMake(_orderLabel.right, _imageView.bottom + 10, view.width * 0.5, 16)
        _dateLabel.font = UIFont.systemFont(ofSize: 12)
        _dateLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_dateLabel)
        
        _priceLabel.frame = CGRectMake(0, _orderLabel.bottom + 10, view.width * 0.5, 16)
        _priceLabel.font = UIFont.systemFont(ofSize: 12)
        _priceLabel.textColor = UIColor.darkGray
        _headerView.addSubview(_priceLabel)
        
        let statusViewHeight:CGFloat = 50
        let statusView:SWOrderStatusView = SWOrderStatusView(frame: CGRectMake(0,_dateLabel.bottom + 30,view.width, statusViewHeight))
        _headerView.addSubview(statusView)
        _statusView = statusView
        
        _headerView.height = statusView.bottom
        _container.contentSize = CGSizeMake(view.width, _headerView.height)
    }
    
    //根据不同状态创建不同的底部功能区
    private func createBottomView(status:SWOrderStatus)
    {
        let bottomViewY:CGFloat = _headerView.height
        let bottomViewHeight:CGFloat = max(view.height - bottomViewY - navigationBarBottom, 100)
        let bottomViewFrame = CGRectMake(0, bottomViewY, view.width, bottomViewHeight)
        if status == .unpaid
        {
            let payView:SWOrderDetailPayView = SWOrderDetailPayView(frame: bottomViewFrame)
            payView.delegate = self
            
            _bottomView = payView
        }
        else if status == .purchased
        {
            let payView:SWOrderDetailUploadingView = SWOrderDetailUploadingView(frame: bottomViewFrame)
            payView.delegate = self
            
            _bottomView = payView
        }
        else if status == .making
        {
            let makingView:SWOrderDetailMakingView = SWOrderDetailMakingView(frame: bottomViewFrame)
            _bottomView = makingView
        }
    }
    
    private func updateView(order:SWOrder)
    {
        _imageView.load("http://mmbiz.qpic.cn/mmbiz_jpg/yhLXShsZlamwfumuM5V5YCMvJcOq9L6UYQjBF5vM5BOX4tmtjnNQ7NyJIC6GBuuLo7SItibetMK9JmsERZmKTuQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1")
        
        if let product = order.products.flatMap({$0 as? SWProduct}).first
        {
            _titleLabel.text = product.title
        }
        
        let orderID:String = order.orderID ?? ""
        _orderLabel.text = "订单:\(orderID)"
        
        let date:String = (order.creationDate as NSDate).formattedDate(withFormat: "YYYY-MM-dd")
        _dateLabel.text = "下单时间：\(date)"
        
        _priceLabel.text = "订单金额：\(order.price)"
        
        _statusView?.status = order.status
    }
    
    private func nullDataViewSetup()
    {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(nullDataViewTapped))
        setupNullDataView(withText: "加载失败，点击重试", container: _container)
        nullDataView?.isUserInteractionEnabled = true
        nullDataView?.addGestureRecognizer(tapGesture)
    }
    
    private func setupRefreshControl()
    {
        let header:MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.reloadData()
        })
        header.lastUpdatedTimeLabel?.isHidden = true
        _container.mj_header = header
    }
    
    
    private func beginRefreshing()
    {
        _container.mj_header?.beginRefreshing()
    }
    
    private func endRefreshing()
    {
        _container.mj_header?.endRefreshing()
    }
    
    
    private func reloadData()
    {
        orderDetailFetch()
    }
    
    //获取订单详情以检查是否真的付款成功
    private func orderDetailFetch()
    {
        let req = SWOrderDetailFetchReq()
        req.orderID = _orderID
        req.successCallback = {[weak self] response,_ in
            if let orderRsp = (response as? SWOrderDetailFetchRsp)?.order,
               let order = SWOrder(response: orderRsp)
            {
                self?.orderFetchSuccess(order: order)
                self?.endRefreshing()
            }
            else
            {
                self?.loadFail()
            }
        }
        req.failCallback = {[weak self] error in
            self?.loadFail()
        }
        
        load(req)
    }

    private func loadFail()
    {
        endRefreshing()
        setNullDataViewHidden(false)
    }
    
    private func orderFetchSuccess(order:SWOrder)
    {
        _status = order.status
        updateView(order: order)
        if order.status == SWOrderStatus.purchased
        {
            SWTransactionManager.sharedManager().uploadOrder(orderID: order.orderID ?? "")
        }
    }
    
    private func purchaseRequisitionFetch()
    {
        let req = SWPurchaseRequisitionFetchReq()
        req.orderID = _orderID
        req.successCallback = {[weak self] response,_ in
            if let requisitionRsp = (response as? SWPurchaseRequisitionFetchRsp)?.requisition,
               let requisition = SWPurchaseRequisition(response: requisitionRsp)
            {
                SVProgressHUD.dismiss()
                let paymentViewController = SWPaymentViewController(requisition: requisition)
                self?.navigationController?.pushViewController(paymentViewController, animated: true)
            }
            else
            {
                SVProgressHUD.showError(withStatus: SWError.DefaultNetworkError.message)
            }
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: error.message)
        }
        SVProgressHUD.show(withStatus: "支付中...")
        load(req)
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if view is SWOrderDetailPayView
        {
            if action == CallbackAction.Tap
            {
                purchaseRequisitionFetch()
            }
            //TODO 测试
            else if action == CallbackAction.Finish
            {
                SWNotificationCenter.post(name: NotificationName.PaySuccess, object: nil, userInfo: [SWKey.orderID:_orderID])
            }
        }
        if view is SWOrderDetailUploadingView
        {
            if action == CallbackAction.Upload
            {
                if let uploader = SWUploadManager.sharedManager().fetchUploader(id: _orderID)
                {
                    trace("开始上传")
                    uploader.resume()
                }
            }
            //TODO 测试
            else if action == CallbackAction.Finish
            {
                //_status = .making
                SWNotificationCenter.post(name: NotificationName.OrderPagesUpdateComplete, object: nil, userInfo: [SWKey.orderID:_orderID])
            }
        }
        
        
    }
    
    @objc private func paySuccessNotification(_ notification:Notification)
    {
        print("paySuccessNotification detail")
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,orderID == _orderID && orderID != ""
        {
            //TODO 之后从服务器获取
            //reloadData()
            #if DEBUG
                _status = .purchased
            #else
                reloadData()
            #endif
        }
    }
    
    @objc private func uploadProgressChangedNotification(_ notification:Notification)
    {
        print("uploadProgressChangedNotification detail")
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,orderID == _orderID && orderID != ""
        {
            let progress:CGFloat = notification.userInfo?[SWKey.progress] as? CGFloat ?? 0
            
            if let uploadingView = _bottomView as? SWOrderDetailUploadingView
            {
                uploadingView.progress = progress
            }
        }
    }
    
    //上传保存完成
    @objc private func orderPagesUpdateCompleteNotification(_ notification:Notification)
    {
        if let orderID = notification.userInfo?[SWKey.orderID] as? String,orderID == _orderID && orderID != ""
        {
            //TODO 之后从服务器获取
            #if DEBUG
                _status = .making
            #else
                reloadData()
            #endif
        }
    }
    
    
    @objc private func nullDataViewTapped()
    {
        reloadData()
        beginRefreshing()
    }
    
}


fileprivate class SWOrderDetailPayView:UIView
{
    weak var delegate:ClickActionDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        let payBtn:UIButton = UIButton(type: .system)
        payBtn.setTitle("去支付", for: .normal)
        payBtn.sizeToFit()
        payBtn.center = bounds.center
        payBtn.addTarget(self, action: #selector(payBtnTapped), for: .touchUpInside)
        addSubview(payBtn)
        
        //TODO 临时测试
        let finishBtn:UIButton = UIButton(type:.system)
        finishBtn.setTitle("支付成功", for: .normal)
        finishBtn.sizeToFit()
        finishBtn.addTarget(self, action: #selector(finishBtnTapped), for: .touchUpInside)
        finishBtn.center = CGPointMake(bounds.center.x, bounds.center.y + 40)
        addSubview(finishBtn)
    }
    
    @objc private func payBtnTapped()
    {
        delegate?.view(self, click: CallbackAction.Tap, argument: nil)
    }
    
    @objc private func finishBtnTapped()
    {
        delegate?.view(self, click: CallbackAction.Finish, argument: nil)
    }
    
}


fileprivate class SWOrderDetailUploadingView:UIView
{
    weak var delegate:ClickActionDelegate?
    
    var progress:CGFloat = 0{
        didSet{
            let p:Int = Int(progress * 100)
            _progressLabel.text = "上传进度\(p)%"
        }
    }
    
    private var _progressLabel:UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        _progressLabel.textColor = UIColor.darkGray
        _progressLabel.font = UIFont.systemFont(ofSize: 14)
        _progressLabel.frame = CGRectMake(10, 20, width, 18)
        addSubview(_progressLabel)
        
        
        let uploadBtn:UIButton = UIButton(type:.system)
        uploadBtn.setTitle("上传", for: .normal)
        uploadBtn.sizeToFit()
        uploadBtn.addTarget(self, action: #selector(uploadBtnTapped), for: .touchUpInside)
        uploadBtn.center = bounds.center
        addSubview(uploadBtn)
        
        //TODO 临时测试
        let finishBtn:UIButton = UIButton(type:.system)
        finishBtn.setTitle("完成", for: .normal)
        finishBtn.sizeToFit()
        finishBtn.addTarget(self, action: #selector(finishBtnTapped), for: .touchUpInside)
        finishBtn.center = CGPointMake(bounds.center.x, bounds.center.y + 40)
        addSubview(finishBtn)
        
        progress = 0
    }
    
    @objc private func uploadBtnTapped()
    {
        delegate?.view(self, click: CallbackAction.Upload, argument: nil)
    }
    
    @objc private func finishBtnTapped()
    {
        delegate?.view(self, click: CallbackAction.Finish, argument: nil)
    }
    
}

fileprivate class SWOrderDetailMakingView:UIView
{
    private var _progressLabel:UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        _progressLabel.textColor = UIColor.darkGray
        _progressLabel.font = UIFont.systemFont(ofSize: 14)
        _progressLabel.text = "咿呀正在拼命赶工"
        _progressLabel.sizeToFit()
        _progressLabel.center = bounds.center
        addSubview(_progressLabel)
    }
    
}


